package com.xgame.server.netty.handler;

import com.xgame.server.netty.QueueInstance;
import com.xgame.server.netty.enity.MsgEntity;
import com.xgame.server.netty.service.CmdMessageService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@ChannelHandler.Sharable
public class ServerHandler extends SimpleChannelInboundHandler<MsgEntity> {

    @Autowired
    private CmdMessageService cmdMessageService;

    private static final Logger log = LoggerFactory.getLogger(ServerHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MsgEntity msg) throws Exception {

        if (msg == null) {
            return;
        }
        msg.setChannel(ctx.channel());

        cmdMessageService.handleMsg(msg);

        /*  目前用不上，等柱子做修改
        // 消息可能较多,可以分几个队列,这里先放一个
        QueueInstance.getInstance().setMessageService(cmdMessageService).offerQueue(msg);
        */
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //channel失效处理,客户端下线或者强制退出等任何情况都触发这个方法
        super.channelInactive(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        ctx.close();
    }

}
